package com.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUC_ReentrantLock_trylock_15 {
    Lock lock = new ReentrantLock();

    void m1(){
        try {
            lock.lock();
            for(int i=0;i<10;i++){
                System.out.println("i="+i);
                TimeUnit.SECONDS.sleep(1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    void m2(){
        /*boolean locked = lock.tryLock();
        System.out.println("m2 invoked...."+locked);//tryLock 方法不管锁定与否，都会执行，根据locked返回值判断是否锁上*/
        boolean locked = false;
        try {
            locked = lock.tryLock(5,TimeUnit.SECONDS);
            System.out.println("m2 invoked...."+locked);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(locked)lock.unlock();;
        }
    }

    public static void main(String[] args) {
        JUC_ReentrantLock_trylock_15 r = new JUC_ReentrantLock_trylock_15();
        new Thread(r::m1,"t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(r::m2,"t2").start();
    }
}
